<template>
  <div class="user-management">
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm"> 
        <el-form-item label="用户名">
          <el-input v-model="searchForm.userName" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="searchForm.phone" placeholder="请输入手机号" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="operation-bar">
      <el-button type="primary" @click="handleAdd">新增用户</el-button>
    </div>

    <el-table :data="tableData" border style="width: 100%" v-loading="loading">
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="username" label="用户名" width="120" />
      <el-table-column prop="phone" label="手机号" width="120" />
      <el-table-column prop="gender" label="性别" width="80">
        <template #default="{ row }">
          {{ row.gender === 1 ? '男' : '女' }}
        </template>
      </el-table-column>
      <el-table-column prop="img" label="头像" width="100">
        <template #default="{ row }">
          <el-image 
            v-if="row.img"
            :src="row.img" 
            :preview-src-list="[row.img]" 
            fit="cover" 
            class="user-avatar"
          />
          <span v-else>暂无头像</span>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column prop="updateTime" label="更新时间" width="180" />
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination"> 
      <!-- 分页组件 -->
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next" 
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 用户表单对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        style="padding: 0 20px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="form.gender">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="isAdd">
          <el-input v-model="form.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="头像" prop="img">
          <el-upload
            class="avatar-uploader"
            :action="null"
            :show-file-list="false"
            :http-request="handleAvatarUpload"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="form.img" :src="form.img" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">支持 jpg、png 格式，大小不超过 2MB</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getUserList, addUser, updateUser, deleteUser, uploadAvatar } from '@/api/user'

// 搜索表单
const searchForm = reactive({
  userName: '',
  phone: ''
})

// 表格数据
const tableData = ref([])
const loading = ref(false) // 加载状态
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 表单对话框
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isAdd = ref(true)
const formRef = ref(null) // 表单引用
const form = reactive({
  id: null,
  username: '',
  phone: '',
  gender: 1,
  password: '',
  img: '',
  createTime: null,
  updateTime: null
})

// 表单验证规则
const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

// 头像上传相关方法
const handleAvatarUpload = async (options) => {
  try {
    const res = await uploadAvatar(options.file)
    if (res.code === 1) {
      form.img = res.data
      ElMessage.success('上传成功')
    }
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error('上传失败')
  }
}

const beforeAvatarUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJpgOrPng) {
    ElMessage.error('头像只能是 JPG 或 PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!')
    return false
  }
  return true
}

// 获取用户列表
const getList = async () => {
  loading.value = true
  try {
    const res = await getUserList({
      userName: searchForm.userName,
      phone: searchForm.phone,
      pageNum: currentPage.value,
      pageSize: pageSize.value
    })
    if (res.code === 1) {
      // 获取用户列表成功,res.data 是响应数据,res.data.records 是用户列表,res.data.total 是总数
      const { records, total: totalCount } = res.data 
      // 过滤掉用户名为admin的用户
      const filteredRecords = records.filter(user => user.username !== 'admin')
      tableData.value = filteredRecords
      // 更新总数，需要减去被过滤的admin用户
      total.value = totalCount - (records.length - filteredRecords.length)
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.userName = ''
  searchForm.phone = ''
  handleSearch()
}

// 新增用户
const handleAdd = () => {
  isAdd.value = true
  dialogTitle.value = '新增用户'
  dialogVisible.value = true
  Object.assign(form, {
    id: null,
    username: '',
    phone: '',
    gender: 1,
    password: '',
    img: '',
    createTime: null,
    updateTime: null
  })
}

// 编辑用户
const handleEdit = (row) => {
  isAdd.value = false
  dialogTitle.value = '编辑用户'
  dialogVisible.value = true
  Object.assign(form, {
    id: row.id,
    username: row.username,
    phone: row.phone,
    gender: row.gender,
    img: row.img
  })
}

// 删除用户
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该用户吗？', '提示', {
    type: 'warning'
  })
    .then(async () => {
      try {
        const res = await deleteUser(row.id)
        if (res.code === 1) {
          ElMessage.success('删除成功')
          getList()
        }
      } catch (error) {
        console.error('删除用户失败:', error)
        ElMessage.error('删除用户失败')
      }
    })
    .catch(() => {})
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const api = isAdd.value ? addUser : updateUser
        // 构建提交的数据对象，确保必填字段不为空
        const submitData = {
          ...form,
          username: form.username?.trim(),
          phone: form.phone?.trim(),
          gender: form.gender || 1,
          password: isAdd.value ? form.password?.trim() : undefined,
          img: form.img || ''
        }
        
        // 验证必填字段
        if (!submitData.username) {
          ElMessage.error('用户名不能为空')
          return
        }
        if (!submitData.phone) {
          ElMessage.error('手机号不能为空')
          return
        }
        if (isAdd.value && !submitData.password) {
          ElMessage.error('密码不能为空')
          return
        }

        console.log('提交的数据：', submitData) // 添加日志
        const res = await api(submitData)
        if (res.code === 1) {
          ElMessage.success(isAdd.value ? '新增成功' : '更新成功')
          dialogVisible.value = false
          getList()
        } else {
          ElMessage.error(res.msg || (isAdd.value ? '新增失败' : '更新失败'))
        }
      } catch (error) {
        console.error(isAdd.value ? '新增用户失败:' : '更新用户失败:', error)
        ElMessage.error(isAdd.value ? '新增用户失败' : '更新用户失败')
      }
    }
  })
}

// 对话框关闭
const handleDialogClose = () => {
  if (formRef.value) {
    formRef.value.resetFields() // 重置表单
  }
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getList()
}

// 初始化
onMounted(() => {
  getList()
})
</script>

<style scoped>
.user-management {
  padding: 24px;
  background: #fff;
  border-radius: 8px;
}

.search-bar {
  margin-bottom: 20px;
}

.operation-bar {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}

.avatar-uploader {
  text-align: center;
}

.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  border-radius: 4px;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}
</style> 